<template>
	<view>
		<view v-if="isload">
			<view class="buydialog-mask" @tap="buydialogChange"></view>
			<view class="buydialog" :class="menuindex > -1 ? 'tabbarbot' : 'notabbarbot'">
				<view class="close" @tap="buydialogChange">
					<image src="/static/img/close.png" class="image" />
				</view>

				<view class="title flex">
					<image :src="nowguige.pic || product.pic" class="img" @tap="previewImage"
						:data-url="nowguige.pic || product.pic" />
					<view class="flex1">
						<view v-if="controller == 'ApiRestaurantShop' || controller == 'ApiRestaurantTakeaway'">
							<view class="price" :style="{ color: t('color1') }">￥{{ totalprice }}</view>
						</view>
						<view v-else>

							<view
								v-if="(shopset && (shopset.price_show_type == '0' || !shopset.price_show_type)) || !shopset">
								<view class="price" :style="{ color: t('color1') }"
									v-if="product.price_type != 1 || nowguige.sell_price > 0">
									<block v-if="product.price_dollar && nowguige.usdsell_price > 0">
										<text style="margin-right: 10rpx;">${{ nowguige.usdsell_price }}</text>
									</block>
									<block v-if="coupons_list.length > 0">
										<text style="font-size: 24rpx;">券后</text>￥{{ discountedUnitPrice.toFixed(2) }}
									</block>
									<block v-else>
										￥{{ nowguige.sell_price }}
									</block>
									<text v-if="nowguige.market_price > nowguige.sell_price" class="t2">￥{{
										nowguige.market_price }}</text>
								</view>
							</view>

							<view v-if="shopset && (shopset.price_show_type == '1' || shopset.price_show_type == '2')">
								<view v-if="product.is_vip == '0'">
									<view class="price" :style="{ color: t('color1') }"
										v-if="product.price_type != 1 || nowguige.sell_price > 0">
										<block v-if="product.price_dollar && nowguige.usdsell_price > 0">
											<text style="margin-right: 10rpx;">${{ nowguige.usdsell_price }}</text>
										</block>
										￥{{ nowguige.sell_price }}
										<text v-if="nowguige.market_price > nowguige.sell_price" class="t2">￥{{
											nowguige.market_price }}</text>
									</view>

									<view class="member flex"
										v-if="shopset.price_show_type == '2' && product.lvprice == 1">
										<view class="member_module flex" :style="'border-color:' + t('color1')">
											<view :style="{ background: t('color1') }"
												class="member_lable flex-y-center">
												{{ nowguige.level_name }}
											</view>
											<view :style="'color:' + t('color1')" class="member_value">
												￥<text>{{ nowguige.sell_price_origin }}</text>
											</view>
										</view>
									</view>
								</view>
								<view v-if="product.is_vip == '1'">
									<view class="member flex">
										<view class="member_module flex" :style="'border-color:' + t('color1')">
											<view :style="{ background: t('color1') }"
												class="member_lable flex-y-center">
												{{ nowguige.level_name }}
											</view>
											<view :style="'color:' + t('color1')" class="member_value"
												style="font-size: 36rpx;">
												￥<text>{{ nowguige.sell_price }}</text>
											</view>
										</view>
									</view>
									<view class="price" :style="{ color: t('color1') }"
										v-if="product.price_type != 1 || nowguige.sell_price > 0">
										<block v-if="product.price_dollar && nowguige.usdsell_price > 0">
											<text style="margin-right: 10rpx;">${{ nowguige.usdsell_price }}</text>
										</block>
										<text :style="product.lvprice == '1' ? 'font-size:30rpx;' : 'font-size:36rpx;'">
											￥{{ nowguige.sell_price_origin }}
										</text>

										<!-- <text v-if="nowguige.market_price > nowguige.sell_price" class="t2">￥{{nowguige.market_price}}</text> -->
									</view>
								</view>
							</view>
						</view>
						<text class="choosename" v-if="product.limit_start > 1"> {{ product.limit_start }}件起售</text>
						<view class="stock" v-if="!shopset || shopset.hide_stock != 1">库存：{{ nowguige.stock }}</view>
						<view class="choosename" v-if="product.limit_start <= 1 && controller != 'Groupby'">已选规格: {{
							nowguige.name }}{{ jltitle }}
						</view>
						<view class="mid-box">
							<text v-if="nowguige.default_presale_status ==0">现货</text>
							<text v-if="nowguige.default_presale_status ==1">预售</text>
							<text class="mid-box-text"
								v-if="nowguige.default_presale_status ==0">{{ estimated_shipping_time }}小时内发货</text>
							<text class="mid-box-text"
								v-if="nowguige.default_presale_status ==1">预售时间{{ nowguige.presale_time }}</text>
						</view>

					</view>
				</view>
				<!--产品描述-->
				<view style="max-height:50vh;overflow:scroll" v-if="product.sellpoint">
					<view class="guigelist flex-col">
						<view class="name">产品描述</view>

						<view class="item flex flex-y-center">
							<view class="description">{{ product.sellpoint }}</view>
						</view>
					</view>
				</view>

				<view v-if="nowguige.balance_price" style="width:94%;margin:10rpx 3%;font-size:24rpx;"
					:style="{ color: t('color1') }">首付款金额：{{ nowguige.advance_price }}元，尾款金额：{{ nowguige.balance_price
					}}元
				</view>
				<view style="max-height:50vh;overflow:scroll">
					<view v-for="(item, index) in guigedata" :key="index" class="guigelist flex-col">
						<view class="name">{{ item.title }}</view>
						<view class="item flex flex-y-center">
							<block v-for="(item2, index2) in item.items" :key="index2">
								<view :data-itemk="item.k" :data-idx="item2.k"
									:class="'item2 ' + (ggselected[item.k] == item2.k ? 'on' : '')" @tap="ggchange">
									{{ item2.title }}
								</view>
							</block>
						</view>
					</view>
				</view>


				<block v-if="product.price_type == 1">
					<button class="addcart" :style="{ backgroundColor: t('color2') }" @tap="showLinkChange">{{
						product.xunjia_text ? product.xunjia_text : '联系TA' }}</button>
				</block>

				<block v-else>
					<view class="buynum flex flex-y-center" v-if="coupons_list.length > 0">
						<view class="flex1">优惠：</view>
						<view class="discount-info">
							<block v-if="isThresholdNotMet">
								<text class="threshold-tip">未达优惠使用门槛</text>
							</block>
							<block v-else>
								<text class="discount-text-left">活动优惠</text><text class="discount-text">{{ discount
								}}元</text>
							</block>
						</view>
					</view>
					<view class="buynum flex flex-y-center">
						<view class="flex1">购买数量：</view>
						<view class="addnum">
							<view class="minus" @tap="gwcminus">
								<image class="img" src="/static/img/cart-minus.png" />
							</view>
							<input class="input" type="number" :value="gwcnum" @input="gwcinput"></input>
							<view class="plus" @tap="gwcplus">
								<image class="img" src="/static/img/cart-plus.png" />
							</view>
						</view>
					</view>
					<view class="tips-text" :style="{ color: t('color1') }"
						v-if="shopset && shopset.showcommission == 1 && nowguige.commission > 0">
						分享好友购买预计可得{{ t('佣金') }}：<text style="font-weight:bold;padding:0 2px">{{ nowguige.commission
						}}</text>{{ nowguige.commission_desc }}
					</view>
					<view class="op">

						<block
							v-if="(nowguige.stock <= 0 && !product.yuding_stock) || (product.yuding_stock && nowguige.stock <= 0 && product.yuding_stock <= 0)">
							<button class="nostock">库存不足</button>
						</block>
						<block v-else>
							<button class="addcart" :style="{ backgroundColor: t('color2') }" @tap="addcart"
								v-if="btntype == 0 && canaddcart">加入购物车</button>
							<button class="tobuy" :style="{ backgroundColor: t('color1') }" @tap="tobuy"
								v-if="btntype == 0">立即购买</button>
							<button class="addcart" :style="{ backgroundColor: t('color2') }" @tap="addcart"
								v-if="btntype == 1">确 定</button>
							<button class="tobuy" :style="{ backgroundColor: t('color1') }" @tap="tobuy"
								v-if="btntype == 2">确 定</button>
							<button class="tobuy" :style="{ backgroundColor: t('color1') }" @tap="toGift"
								v-if="btntype == 3">确 定</button>
							<button class="tobuy" :style="{ backgroundColor: t('color1') }" @tap="toZone"
								v-if="btntype == 4">确 定</button>
						</block>
					</view>
				</block>
			</view>
		</view>
		<loading v-if="loading"></loading>
	</view>
</template>
<script>
	var app = getApp();
	export default {
		data() {
			return {
				ks: '',
				product: {},
				guigelist: {},
				guigedata: {},
				ggselected: {},
				nowguige: {},
				jialiaodata: [],
				jlprice: 0,
				jltitle: '',
				gwcnum: 1,
				isload: false,
				loading: false,
				canaddcart: true,
				shopset: {},
				glassrecord: {},
				showglass: false,
				totalprice: 0,
				jlselected: [],
				hasglassrecord: 0,
				grid: 0,
				coupons_list: [],
				youhui_coupon_id: '',
				discount: 0,
				isThresholdNotMet: false,
				newPrice: 0,
				discountedUnitPrice: 0,
				estimated_shipping_time: 0,
				default_presale_status: 0,
				isPresale: null,
				presale_time: null,
				procode: 0, //秒杀等商品原id
			}
		},
		props: {
			canbuy: {
				default: ''
			},
			btntype: {
				default: 0
			},
			menuindex: {
				default: -1
			},
			controller: {
				default: 'Shop'
			},
			needaddcart: {
				default: true
			},
			proid: {},
			currentTab: { // 接收 currentTab
				type: Number,
				default: 0
			}
		},
		mounted: function() {
			var that = this;
			uni.$on('getglassrecord', function(data) {
				that.getglassrecord()
			});

			that.getdata();
			that.getlist()
		},
		beforeDestroy() {
			uni.$off('getglassrecord')

		},

		methods: {
			getlist() {
				var that = this;
				var id = that.proid;
				that.loading = true;
				app.get(that.controller + '/product', {
					id: id,
				}, function(res) {
					that.loading = false;
					that.product = res.product;
					that.procode = res.product.procode
					that.estimated_shipping_time = res.product.estimated_shipping_time
					that.coupons_list = res.couponlist
					that.calculateDiscount();
				});
			},

			isValidNumber(value) {
				// 检查是否为数字且不是 NaN
				return typeof value === 'number' && !isNaN(value);
			},
			// 计算优惠金额
			calculateDiscount() {
			  // 1. 确保数值类型安全
			  const sellPrice = parseFloat(this.nowguige?.sell_price) || 0;
			  const gwcnum = parseInt(this.gwcnum) || 0;
			  
			  // 2. 计算订单总金额
			  this.totalPrice = sellPrice * gwcnum;
			  
			  let maxDiscount = 0;
			  let bestCoupon = null;
			  this.isThresholdNotMet = true;
			  this.youhui_coupon_id = 0; // 默认0表示未选择优惠券
			  
			  // 3. 检查所有优惠券（包含有门槛和无门槛）
			  this.coupons_list?.forEach((coupon) => {
			    try {
			      const minNum = parseInt(coupon.minnum) || 0;
			      const minPrice = parseFloat(coupon.minprice) || 0;
			      const couponMoney = parseFloat(coupon.money) || 0;
			      
			      // 情况1：满足门槛条件
			      const meetsThreshold = gwcnum >= minNum && this.totalPrice >= minPrice;
			      
			      // 情况2：无门槛优惠券（minNum和minPrice都为0）
			      const isNoThreshold = minNum === 0 && minPrice === 0;
			      
			      if (meetsThreshold || isNoThreshold) {
			        this.isThresholdNotMet = false;
			        
			        // 选择最优优惠券逻辑
			        if (couponMoney > maxDiscount || 
			            (couponMoney === maxDiscount && minPrice <= (bestCoupon?.minprice || Infinity))) {
			          maxDiscount = couponMoney;
			          bestCoupon = coupon;
			          this.youhui_coupon_id = coupon.id;
			        }
			      }
			    } catch (e) {
			      console.error('优惠券解析错误:', coupon, e);
			    }
			  });
			  
			  // 4. 更新优惠金额和最终价格
			  this.discount = maxDiscount;
			  this.usedCoupon = bestCoupon || null;
			  
			  // 5. 计算最终价格（确保不小于0）
			  this.newPrice = Math.max(sellPrice * gwcnum - this.discount, 0);
			  
			  // 6. 计算折后单价（安全除法）
			  this.discountedUnitPrice = gwcnum > 0 ? 
			    this.newPrice / gwcnum : 
			    sellPrice;
			  
			  // 调试日志
			  if (bestCoupon) {
			    console.log('应用优惠券:', {
			      id: this.youhui_coupon_id,
			      name: bestCoupon.name,
			      discount: maxDiscount,
			      finalPrice: this.newPrice
			    });
			  } else {
			    console.log('未使用优惠券');
			  }
			},

			getdata: function() {
				var that = this;
				if (this.controller == 'Shop' && app.globalData.isdouyin == 1) {
					app.showLoading('加载中');
					app.post('Shop/getDouyinProductId', {
						proid: that.proid
					}, function(res) {
						app.showLoading(false);
						if (res.status == 1) {
							tt.openEcGood({
								promotionId: res.douyin_product_id
							});
						} else {
							app.alert(res.msg)
						}
					});
					return;
				}

				that.loading = true;
				app.post(that.controller + '/getproductdetail', {
					id: that.proid
				}, function(res) {
					that.loading = false;
					that.product = res.product;
					that.shopset = res.shopset;
					if (!that.product.limit_start) {
						that.product.limit_start = 1;
					}
					that.guigelist = res.guigelist;
					that.guigedata = res.guigedata ? res.guigedata : [];
					var guigedata = res.guigedata ? res.guigedata : [];
					var ggselected = [];
					if (guigedata.length > 0) {
						for (var i = 0; i < guigedata.length; i++) {
							ggselected.push(0);
						}
						that.ks = ggselected.join(',');
						that.nowguige = that.guigelist[that.ks];

						that.ggselected = ggselected;
					}
					if (that.controller == 'Groupby') {
						that.nowguige = {
							...res.product
						};
					}
					console.log(that.nowguige, 'that.nowguige');
					if (that.nowguige.limit_start > 0) {
						that.gwcnum = that.nowguige.limit_start;
					} else {
						that.gwcnum = that.product.limit_start;
					}
					that.isload = true;
					if (that.product.freighttype == 3 || that.product.freighttype == 4 || that.product.freighttype == 5) { //虚拟商品不能加入购物车
						that.canaddcart = false;
					}
					//是否是眼睛产品
					if (that.product.product_type == 1) {
						that.showglass = true
						that.getglassrecord()
					}
					if (that.controller == 'ApiRestaurantShop' || that.controller == 'ApiRestaurantTakeaway') {
						that.jialiaodata = res.jialiaodata;
						that.totalprice = that.nowguige.sell_price;
					}
				});
			},
			buydialogChange: function() {
				this.$emit('buydialogChange');
			},
			getglassrecord: function(e) {
				var that = this;
				var grid = app.getCache('_glass_record_id');
				// console.log('grid='+grid);
				// if(!grid || grid==0){
				// 	return;
				// }
				console.log('grid=' + grid)
				if (that.showglass === true && (!that.glassrecord || (that.glassrecord && that.glassrecord.id !=
						grid))) {
					app.post('ApiGlass/myrecord', {
						pagenum: 1,
						listrow: 1,
						id: grid
					}, function(resG) {
						var datalist = resG.data;
						if (datalist.length > 0) {
							that.hasglassrecord = 1;
							if (grid > 0) {
								that.grid = grid
								for (let i in datalist) {
									if (datalist[i].id == grid) {
										that.glassrecord = datalist[i]
									}
								}
							}
						}
					});
				}
			},
			showLinkChange: function() {
				this.$emit('showLinkChange');
			},
			//选择规格
			ggchange: function(e) {

				var idx = e.currentTarget.dataset.idx;
				var itemk = e.currentTarget.dataset.itemk;
				var ggselected = this.ggselected;
				ggselected[itemk] = idx;
				var ks = ggselected.join(',');
				this.ggselected = ggselected;
				this.ks = ks;
				this.nowguige = this.guigelist[this.ks];
				this.isPresale = this.nowguige.default_presale_status;
				this.presale_time = this.nowguige.presale_time;
				// console.log(this.guigelist, 'this.guigelist');
				if (this.nowguige.limit_start > 0) {
					if (this.gwcnum < this.nowguige.limit_start) {
						this.gwcnum = this.nowguige.limit_start;
					}
				}
				this.totalprice = parseFloat(parseFloat(this.nowguige.sell_price) + this.jlprice).toFixed(2);
				this.calculateDiscount();
			},
			jlchange: function(index) {
				this.jialiaodata[index].active = this.jialiaodata[index].active == true ? false : true;
				var jlprice = 0;
				var title = '';
				let jlselect = [];
				for (let i = 0; i < this.jialiaodata.length; i++) {
					if (this.jialiaodata[i].active) {
						jlprice = jlprice + parseFloat(this.jialiaodata[i].price);
						title += ',' + this.jialiaodata[i].jltitle;
						jlselect.push(this.jialiaodata[i]);
					}
				}
				this.jltitle = title;
				this.jlprice = jlprice;
				this.totalprice = parseFloat(parseFloat(this.nowguige.sell_price) + jlprice).toFixed(2);
				this.jlselected = jlselect;
				this.jialiaodata = this.jialiaodata;
			},
			//送礼
			toGift: function(e) {
			    var that = this;
			    if (that.canbuy) {
			        app.error(that.canbuy)
			        that.$emit('buydialogChange');
			        return;
			    }
			
			    var ks = that.ks; // 选中的规格索引
			    var proid = that.product.id;
			    var ggid = that.guigelist[ks].id; // 选中规格的ID
			    var stock = that.guigelist[ks].stock; // 选中规格的库存
			    var name = that.product.name;
			    var pic = that.product.pic;
			    var sell_price = that.guigelist[ks].sell_price || that.product.sell_price;
			    var sellpoint = that.product.sellpoint;
			    var num = that.gwcnum;
			
			    // 默认购买数量为1
			    if (num < 1) num = 1;
			
			    // 检查库存
			    if ((stock < num && !that.product.shop_yuding) ||
			        (that.product.shop_yuding && stock <= num && that.product.yuding_stock <= num)) {
			        app.error('库存不足');
			        return;
			    }
			
			    // 构造商品规格数据
			    var prodataArray = []; // 用于存放多个商品的数据
			    var prodata = proid + ',' + ggid + ',' + num;
			    if (that.showglass) {
			        if (that.grid > 0) {
			            prodata += ',' + that.grid;
			        }
			    }
			    // 将当前商品的prodata添加到prodataArray数组
			    prodataArray.push(prodata);
			
			    let gift = {
			        proid: proid,
			        ggid: ggid,
			        num: num,
			        name: name,
			        sell_price: sell_price,
			        sellpoint: sellpoint,
			        pic: pic,
			        ks: ks,
			        nowguige: that.nowguige
			    }
			
			    // 检查是否已存在该商品对象（根据 proid 或 ggid 判断）
			    let existingGiftIndex = app.globalData.giftdata.findIndex(item => item.proid === gift.proid && item
			        .ggid === gift.ggid);
			
			    if (existingGiftIndex !== -1) {
			        // 商品已存在，num 加 1
			        app.globalData.giftdata[existingGiftIndex].num += num;
			    } else {
			        // 商品不存在，追加到 giftdata 数组
			        app.globalData.giftdata.push(gift);
			    }
			
			    // 如果有多个商品，继续拼接
			    if (that.moreGifts) {
			        // 遍历更多商品并加入到 prodataArray 中
			        that.moreGifts.forEach(item => {
			            let additionalProdata = item.proid + ',' + item.ggid + ',' + item.num;
			            if (item.grid > 0) {
			                additionalProdata += ',' + item.grid;
			            }
			            prodataArray.push(additionalProdata);
			        });
			    }
			
			    // 将 prodataArray 数组用 '-' 拼接成一个字符串
			    var finalProdata = prodataArray.join('-');
			
			    // 领券
			    if (that.youhui_coupon_id) {
			        if (!app.globalData.pro_ids.includes(that.youhui_coupon_id)) {
			            app.post('Coupon/getcoupon', {
			                id: that.youhui_coupon_id,
			            }, function(res) {
			                app.globalData.pro_ids.push(that.youhui_coupon_id);
			            });
			        }
			    }
			
			    this.$emit('buydialogChange');
			    app.goto('/pagesZone/gift/gift_present?youhui_coupon_id=' + that.youhui_coupon_id + "&prodata=" +
			        finalProdata);
			},

			toZone: function(e) {
			    var that = this;
			    if (that.canbuy) {
			        app.error(that.canbuy)
			        that.$emit('buydialogChange');
			        return;
			    }
			    var ks = that.ks; // 选中的规格索引
			    var proid = that.product.id;
			    var ggid = that.guigelist[ks].id; // 选中规格的ID
			    var stock = that.guigelist[ks].stock; // 选中规格的库存
			    var name = that.product.name;
			    var pic = that.product.pic;
			    var sell_price = that.guigelist[ks].sell_price || that.product.sell_price;
			    var sellpoint = that.product.sellpoint;
			    var num = that.gwcnum;
			
			    // 默认购买数量为1
			    if (num < 1) num = 1;
			
			    // 计算总数量（包括购物车中已存在的同款商品）
			    let totalQuantity = num;
			    const existingItem = app.globalData.giftdata.find(item => 
			        item.proid === proid && item.ggid === ggid);
			    
			    if (existingItem) {
			        totalQuantity += existingItem.num;
			    }
			
			    // 检查库存（考虑购物车中已有数量）
			    if ((stock < totalQuantity && !that.product.shop_yuding) ||
			        (that.product.shop_yuding && stock <= totalQuantity && that.product.yuding_stock <= totalQuantity)) {
			        app.error('库存不足');
			        return;
			    }
			
			    // 构造当前商品数据
			    var currentProdata = proid + ',' + ggid + ',' + num;
			    if (that.showglass) {
			        if (that.grid > 0) {
			            currentProdata += ',' + that.grid;
			        }
			    }
			    
			    let gift = {
			        proid: proid,
			        ggid: ggid,
			        num: num,
			        name: name,
			        sell_price: sell_price,
			        sellpoint: sellpoint,
			        pic: pic,
			        ks: ks,
			        nowguige: that.nowguige
			    }
			
			    // 检查是否已存在该商品对象
			    let existingGiftIndex = app.globalData.giftdata.findIndex(item => 
			        item.proid === gift.proid && item.ggid === gift.ggid);
			    
			    // 获取现有的prodata参数（如果有）
			    let existingProdata = '';
			    if (app.globalData.prodata) {
			        existingProdata = app.globalData.prodata + '-';
			    }
			
			    if (existingGiftIndex !== -1) {
			        // 商品已存在，更新数量和prodata
			        app.globalData.giftdata[existingGiftIndex].num += num;
			        
			        // 更新prodata中的数量
			        let prodataArray = existingProdata.split('-');
			        let updated = false;
			        prodataArray = prodataArray.map(item => {
			            let parts = item.split(',');
			            if (parts[0] == proid && parts[1] == ggid) {
			                parts[2] = parseInt(parts[2]) + num;
			                updated = true;
			                return parts.join(',');
			            }
			            return item;
			        });
			        
			        if (!updated) {
			            prodataArray.push(currentProdata);
			        }
			        existingProdata = prodataArray.join('-');
			    } else {
			        // 商品不存在，追加到giftdata数组和prodata
			        app.globalData.giftdata.push(gift);
			        existingProdata = existingProdata ? existingProdata + currentProdata : currentProdata;
			    }
			    
			    // 保存更新后的prodata
			    app.globalData.prodata = existingProdata;
			    
			    this.$emit('buydialogChange');
			    let currentTab = that.currentTab;
			    let gift_is_secret = app.globalData.gift_is_secret;
			    let gift_num = app.globalData.gift_num;
			    
			    //领券
			    if (that.youhui_coupon_id) {
			        if (!app.globalData.pro_ids.includes(that.youhui_coupon_id)) {
			            app.post('Coupon/getcoupon', {
			                id: that.youhui_coupon_id,
			            }, function(res) {
			                app.globalData.pro_ids.push(that.youhui_coupon_id);
			            });
			        }
			    }
			    
			    uni.redirectTo({
			        url: '/pagesZone/gift/gift_present?currentTab=' + currentTab + '&gift_is_secret=' +
			            gift_is_secret + "&gift_num=" + gift_num + "&prodata=" + existingProdata +
			            '&youhui_coupon_id=' + that.youhui_coupon_id
			    })
			},
			tobuy: function(e) {
				var that = this;
				if (that.canbuy) {
					app.error(that.canbuy)
					that.$emit('buydialogChange');
					return;
				}
				var ks = that.ks;
				var proid = that.product.id;
				var num = that.gwcnum;
				
				//领券
				if (that.youhui_coupon_id) {
					app.post('Coupon/getcoupon', {
						id: that.youhui_coupon_id,
					}, function(res) {

					});
				}
				if (this.controller == 'Groupby') {

					if (num < 1) num = 1;
					if (that.product.stock < num) {
						app.error('库存不足');
						return;
					}
					var prodata = proid + ',' + num;
				} else {
					var ggid = that.guigelist[ks].id;
					var stock = that.guigelist[ks].stock;

					if (num < 1) num = 1;
					if ((stock < num && !that.product.shop_yuding) || (that.product.shop_yuding && stock <= num && that
							.product.yuding_stock <=
							num)) {
						app.error('库存不足');
						return;
					}
					var prodata = proid + ',' + ggid + ',' + num + ',' + app.globalData.commerce_mid + ',' + app.globalData.commerce_type;
					if (that.showglass) {
						if (that.grid > 0) {
							prodata += ',' + that.grid;
						}
					}
				}
				that.$emit('buydialogChange');
				if (that.controller == 'Shop') {
					app.goto('/pages/shop/buy?prodata=' + prodata + '&youhui_coupon_id=' + that.youhui_coupon_id);
				} else if (that.controller == 'Seckill') {
					app.goto('/pagesExt/seckill/buy?prodata=' + prodata + '&youhui_coupon_id=' + that
					.youhui_coupon_id);
				} else if (that.controller == 'Groupby') {
					app.goto('/pagesExt/groupby/buy?prodata=' + prodata + '&youhui_coupon_id=' + that
					.youhui_coupon_id);
				}
			},
			//加入购物车操作
			addcart: function() {
				var that = this;
				var ks = that.ks;
				var num = that.gwcnum;
				var proid = that.product.id;
				var ggid = that.guigelist[ks].id;
				var stock = that.guigelist[ks].stock;


				if (num < 1) num = 1;
				if (stock < num) {
					app.error('库存不足');
					return;
				}
				var glass_record_id = 0;
				if (that.showglass) {
					glass_record_id = that.grid;
				}
				var ctl = this.controller;
				if (this.needaddcart) {
					app.post(ctl + '/addcart', {
						proid: proid,
						ggid: ggid,
						num: num,
						glass_record_id: glass_record_id,
						commerce_mid: app.globalData.commerce_mid,
						commerce_type:app.globalData.commerce_type,
					}, function(res) {
						 // app.globalData.commerce_mid = 0
						 // app.globalData.commerce_type = 0
						if (res.status == 1) {
							app.success('添加成功');
							that.$emit('addcart', {
								proid: proid,
								ggid: ggid,
								num: num,
								jlprice: that.jlprice,
								jltitle: that.jltitle
							});
							that.$emit('buydialogChange');
						} else {
							app.error(res.msg);
						}
					});
				} else {
					that.$emit('addcart', {
						proid: proid,
						ggid: ggid,
						num: num,
						jlprice: that.jlprice,
						jltitle: that.jltitle
					});
					that.$emit('buydialogChange');
				}
			},
			//加
			gwcplus: function(e) {
				var gwcnum = this.gwcnum + 1;
				var ks = this.ks;
				if (this.controller == 'Groupby') {
					if (gwcnum > this.product.stock) {
						app.error('库存不足');
						return 1;
					}
					this.gwcnum = this.gwcnum + 1;
					return
				}
				if (gwcnum > this.guigelist[ks].stock) {
					app.error('库存不足');
					return 1;
				}
				if (this.product.perlimitdan > 0 && gwcnum > this.product.perlimitdan) {
					app.error('每单限购' + this.product.perlimitdan + '件');
					return 1;
				}
				if (this.product.perlimit > 0 && gwcnum > this.product.perlimit) {
					app.error('每单限购' + this.product.perlimit + '件');
					return 1;
				}
				this.gwcnum = this.gwcnum + 1;
				this.calculateDiscount();
			},
			//减
			gwcminus: function(e) {
				if (this.gwcnum - 1 == 0) {
					return;
				}
				var gwcnum = this.gwcnum - 1;
				var ks = this.ks;
				if (this.controller == 'Groupby') {
					if (gwcnum <= this.product.limit_start - 1) {
						if (this.product.limit_start > 1) {
							app.error('该商品' + this.product.limit_start + '件起售');
						}
						return;
					}
					this.gwcnum = this.gwcnum - 1;
					return
				}

				if (this.nowguige.limit_start > 0) {
					if (gwcnum <= this.nowguige.limit_start - 1) {
						if (this.nowguige.limit_start > 1) {
							app.error('该规格' + this.nowguige.limit_start + '件起售');
						}
						return;
					}
				} else {
					if (gwcnum <= this.product.limit_start - 1) {
						if (this.product.limit_start > 1) {
							app.error('该商品' + this.product.limit_start + '件起售');
						}
						return;
					}
				}

				this.gwcnum = this.gwcnum - 1;
				this.calculateDiscount();
			},
			//输入
			gwcinput: function(e) {
				if (this.controller == 'Groupby') {
					var ks = this.ks;
					var gwcnum = parseInt(e.detail.value);
					if (gwcnum < 1) return 1;
					if (gwcnum > this.product.stock) {
						return this.product.stock > 0 ? this.product.stock : 1;
					}
					this.gwcnum = gwcnum;
					return
				}
				var ks = this.ks;
				var gwcnum = parseInt(e.detail.value);
				if (gwcnum < 1) return 1;
				if (gwcnum > this.guigelist[ks].stock) {
					return this.guigelist[ks].stock > 0 ? this.guigelist[ks].stock : 1;
				}
				if (this.nowguige.limit_start > 0) {
					if (gwcnum <= this.nowguige.limit_start - 1) {
						if (this.nowguige.limit_start > 1) {
							app.error('该规格' + this.nowguige.limit_start + '件起售');
						}
						gwcnum = this.nowguige.limit_start;
					}
				} else {
					if (gwcnum <= this.product.limit_start - 1) {
						if (this.product.limit_start > 1) {
							app.error('该商品' + this.product.limit_start + '件起售');
						}
						gwcnum = this.product.limit_start;
					}

				}
				if (this.product.perlimitdan > 0 && gwcnum > this.product.perlimitdan) {
					app.error('每单限购' + this.product.perlimitdan + '件');
					gwcnum = this.product.perlimitdan;
				}
				if (this.product.perlimit > 0 && gwcnum > this.product.perlimit) {
					app.error('每单限购' + this.product.perlimit + '件');
					return 1;
				}
				this.gwcnum = gwcnum;
				this.calculateDiscount();
			},
		}
	}
</script>
<style scoped>
	.buydialog-mask {
		position: fixed;
		top: 0px;
		left: 0px;
		width: 100%;
		background: rgba(0, 0, 0, 0.5);
		bottom: 0px;
		z-index: 10
	}

	.buydialog {
		position: fixed;
		width: 100%;
		left: 0px;
		bottom: 0px;
		background: #fff;
		z-index: 11;
		border-radius: 20rpx 20rpx 0px 0px
	}

	.buydialog .close {
		position: absolute;
		top: 0;
		right: 0;
		padding: 20rpx;
		z-index: 12
	}

	.buydialog .close .image {
		width: 30rpx;
		height: 30rpx;
	}

	.buydialog .title {
		width: 94%;
		position: relative;
		margin: 0 3%;
		padding: 15rpx 0 0 0;
		border-bottom: 0;
	}

	.buydialog .title .img {
		width: 160rpx;
		height: 160rpx;
		border-radius: 10rpx;
		border: 0 #e5e5e5 solid;
		background-color: #fff;
		flex-shrink: 0;
		margin-right: 15rpx;
	}

	.buydialog .title .price {
		width: 100%;
		font-size: 36rpx;
		color: #FC4343;
		overflow: hidden;
	}

	.buydialog .title .price .t1 {
		font-size: 26rpx
	}

	.buydialog .title .price .t2 {
		font-size: 26rpx;
		text-decoration: line-through;
		color: #aaa;
		margin-left: 6rpx;
	}

	.buydialog .title .choosename {
		width: 100%;
		font-size: 24rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 42rpx;
		color: #888888
	}

	.buydialog .title .stock {
		width: 100%;
		font-size: 24rpx;
		height: 42rpx;
		line-height: 42rpx;
		color: #888888
	}

	.buydialog .guigelist {
		width: 94%;
		position: relative;
		margin: 0 3%;
		padding: 0px 0px 10px 0px;
		border-bottom: 0;
	}

	.buydialog .guigelist .name {
		height: 70rpx;
		line-height: 70rpx;
	}

	.buydialog .guigelist .item {
		font-size: 30rpx;
		color: #333;
		flex-wrap: wrap
	}

	.buydialog .guigelist .item2 {
		height: 60rpx;
		line-height: 60rpx;
		margin-bottom: 4px;
		border: 0;
		border-radius: 4rpx;
		padding: 0 40rpx;
		color: #666666;
		margin-right: 10rpx;
		font-size: 26rpx;
		background: #F4F4F4;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.buydialog .guigelist .on {
		color: #FC4343;
		background: rgba(252, 67, 67, 0.1);
		font-weight: bold
	}

	.buydialog .buynum {
		width: 94%;
		position: relative;
		margin: 0 3%;
		padding: 10px 0px 10px 0px;
	}

	.buydialog .addnum {
		font-size: 30rpx;
		color: #666;
		width: auto;
		display: flex;
		align-items: center
	}

	.buydialog .addnum .plus {
		width: 65rpx;
		height: 48rpx;
		background: #F6F8F7;
		display: flex;
		align-items: center;
		justify-content: center
	}

	.buydialog .addnum .minus {
		width: 65rpx;
		height: 48rpx;
		background: #F6F8F7;
		display: flex;
		align-items: center;
		justify-content: center
	}

	.buydialog .addnum .img {
		width: 24rpx;
		height: 24rpx
	}

	.buydialog .addnum .input {
		flex: 1;
		width: 50rpx;
		border: 0;
		text-align: center;
		color: #2B2B2B;
		font-size: 28rpx;
		margin: 0 15rpx;
	}

	.buydialog .tips-text {
		display: inline-block;
		margin-top: 20rpx;
		margin-bottom: 10rpx;
		border-radius: 10rpx;
		font-size: 20rpx;
		height: 44rpx;
		line-height: 44rpx;
		padding: 0 20rpx
	}

	.buydialog .op {
		width: 90%;
		margin: 20rpx 5%;
		border-radius: 36rpx;
		overflow: hidden;
		display: flex;
		margin-top: 60rpx;
	}

	.buydialog .addcart {
		flex: 1;
		height: 72rpx;
		line-height: 72rpx;
		color: #fff;
		border-radius: 0px;
		border: none;
		font-size: 28rpx;
		font-weight: bold
	}

	.buydialog .tobuy {
		flex: 1;
		height: 72rpx;
		line-height: 72rpx;
		color: #fff;
		border-radius: 0px;
		border: none;
		font-size: 28rpx;
		font-weight: bold
	}

	.buydialog .nostock {
		flex: 1;
		height: 72rpx;
		line-height: 72rpx;
		background: #aaa;
		color: #fff;
		border-radius: 0px;
		border: none;
	}

	.glassinfo {
		width: 94%;
		margin: 10rpx 3% 0 3%;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12rpx;
		background: #f4f4f4;
		border-radius: 10rpx;
		font-size: 34rpx;
	}

	.glassinfo .g-title {
		font-weight: bold;
	}

	.glassinfo image {
		width: 42rpx;
		height: 42rpx;
		padding-top: 10rpx;
	}

	.description {
		width: 100%;
		font-size: 24rpx;
		height: 42rpx;
		line-height: 42rpx;
		color: #888888;
	}

	.member {
		padding: 5rpx 0;
		width: 100%;
	}

	.member_module {
		position: relative;
		border-radius: 8rpx;
		border: 1rpx solid #fd4a46;
		overflow: hidden;
		box-sizing: content-box;
	}

	.member_lable {
		height: 100%;
		font-size: 22rpx;
		color: #fff;
		background: #fd4a46;
		padding: 0 15rpx;
	}

	.member_value {
		padding: 0 15rpx;
		font-size: 30rpx;
		color: #fd4a46;
	}

	.discount-text-left {
		color: #808080;
	}

	.discount-text {
		color: #FC4343;
	}

	.mid-box {
		background-color: #fff;
		padding-bottom: 20rpx;
	}

	.mid-box-text {
		margin-left: 10rpx;
		font-size: 26rpx;
		color: #888;
	}
</style>